<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="初审" prop="firstReview" >
        <el-select v-model="queryParams.firstReview" placeholder="请选择初审" clearable>
          <el-option label="待审核" value="1"></el-option>
          <el-option label="未通过" value="2"></el-option>
          <el-option label="通过" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生姓名" prop="name" >
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号码" prop="idNumber" label-width="100px">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参赛组别" prop="competitionGroup">
        <el-select v-model="queryParams.competitionGroup" placeholder="请选择参赛组别" clearable>
          <el-option
            v-for="dict in dict.type.competition_group"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作品名称" prop="workName">
        <el-input
          v-model="queryParams.workName"
          placeholder="请输入作品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就读学校" prop="school">
        <el-input
          v-model="queryParams.school"
          placeholder="请输入就读学校"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:registration:export']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:registration:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="registrationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" align="center" prop="name" fixed/>
      <el-table-column label="身份证号码" align="center" prop="idNumber" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="参赛组别" align="center" prop="competitionGroup" />
      <el-table-column label="参赛编号" align="center" prop="competitionNumber" />
      <el-table-column label="作品类型" align="center" prop="workType" />
      <el-table-column label="其他作品类型" align="center" prop="otherWorkType" />
      <el-table-column label="作品名称" align="center" prop="workName" />
      <el-table-column label="就读学校" align="center" prop="school" />
      <el-table-column label="学生家长" align="center" prop="parentName" />
      <el-table-column label="家长电话" align="center" prop="parentPhone" />
      <el-table-column label="作品缩略图" align="center" prop="thumbnail">
        <template slot-scope="scope">
          <div>
            <div>
              <el-image
                v-if="scope.row.thumbnail && scope.row.thumbnail.split(',').filter(t => !isVideo(t.trim())).length > 0 "
                style="width: 100px; height: 100px; margin-right: 10px;"
                :src="`${baseUrl}${scope.row.thumbnail.split(',').filter(t => !isVideo(t.trim()))[0].trim()}`"
                :preview-src-list="scope.row.thumbnail.split(',').filter(t => !isVideo(t.trim())).map(t => `${baseUrl}${t.trim()}`)"
                fit="cover"
              />
            </div>
            <div v-for="(item,index) in scope.row.thumbnail && scope.row.thumbnail.split(',').filter(t => isVideo(t.trim()))">
              <video
                style="width: 200px; height: 150px; margin-right: 10px;"
                :src="`${baseUrl}${item}`"
                controls
                muted
                loop
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="初审" align="center" prop="firstReview" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.firstReview === '3' ? 'success' : scope.row.firstReview === '2' ? 'danger' : 'info'">
            {{ scope.row.firstReview === '3' ? '通过' : scope.row.firstReview === '2' ? '未通过' : '待审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批意见" align="center" prop="firstOption" />

      <!--      <el-table-column label="作品简介" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showApprovalDialog(scope.row)"
            v-hasPermi="['project:registration:edit']"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:registration:edit']"
          >修改</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生报名信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学生姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入学生姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idNumber" label-width="100px">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-input v-model="form.grade" placeholder="请输入年级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参赛组别" prop="competitionGroup">
              <el-select v-model="form.competitionGroup" placeholder="请选择参赛组别">
                <el-option
                  v-for="dict in dict.type.competition_group"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="通讯地址" prop="address">
              <el-input v-model="form.address" placeholder="通讯地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品尺寸"  label-width="100px">
              <div style="display: flex;align-items: center;">
                宽 <el-input-number v-model="form.width" placeholder="宽" />
                高<el-input-number v-model="form.height" placeholder="高" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="参赛编号" prop="competitionNumber">
              <el-input v-model="form.competitionNumber" placeholder="请输入参赛编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品类型" prop="workType">
              <el-select v-model="form.workType" placeholder="请选择作品类型">
                <el-option
                  v-for="dict in dict.type.work_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="其他作品类型" prop="otherWorkType" label-width="100px">
              <el-input v-model="form.otherWorkType" placeholder="请输入其他作品类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品名称" prop="workName">
              <el-input v-model="form.workName" placeholder="请输入作品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="就读学校" prop="school">
              <el-input v-model="form.school" placeholder="请输入就读学校" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生家长" prop="parentName">
              <el-input v-model="form.parentName" placeholder="请输入学生家长" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="家长电话" prop="parentPhone">
              <el-input v-model="form.parentPhone" placeholder="请输入家长电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品" prop="thumbnail">
              <image-upload v-model="form.thumbnail" :limit=3 />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="指导老师" prop="teacher">
              <el-input v-model="form.teacher"    placeholder="指导老师" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品简介" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog :title="'审批'" :visible.sync="approvalDialogVisible" width="300px" style="margin-top: 200px">
      <el-radio-group v-model="selectedApproval" style="text-align: center;">
        <el-radio label="3">通过</el-radio>
        <el-radio label="2">不通过</el-radio>
        <el-radio label="1">未审核</el-radio>
      </el-radio-group>
      <el-input
        v-model="approvalOpinion"
        type="textarea"
        :rows="4"
        placeholder="请输入审批意见"
        style="margin-top: 10px;"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="approvalDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleApprove">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 学生报名信息导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRegistration, getRegistration, delRegistration, addRegistration, updateRegistration } from "@/api/project/registration";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";

export default {
  dicts: ['competition_group', 'work_type'],
  name: "FirstReview",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生报名信息表格数据
      registrationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      videoExtensions: ['mp4', 'webm', 'ogg'], // 支持的视频格式
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idNumber: null,
        competitionGroup: null,
        workType: null,
        workName: null,
        school: null,
        preliminaryReview: '3',
        firstReview: null,
        finalReview: null,
      },
      baseUrl: process.env.VUE_APP_BASE_API ,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        idNumber: [
          { required: true, message: "身份证号码不能为空", trigger: "blur" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "blur" }
        ],
        competitionGroup: [
          { required: true, message: "参赛组别不能为空", trigger: "blur" }
        ],
        competitionNumber: [
          { required: true, message: "参赛编号不能为空", trigger: "blur" }
        ],
        workType: [
          { required: true, message: "作品类型不能为空", trigger: "change" }
        ],
        workName: [
          { required: true, message: "作品名称不能为空", trigger: "blur" }
        ],
        school: [
          { required: true, message: "就读学校不能为空", trigger: "blur" }
        ],
        parentName: [
          { required: true, message: "学生家长不能为空", trigger: "blur" }
        ],
        parentPhone: [
          { required: true, message: "家长电话不能为空", trigger: "blur" }
        ],
      },
      approvalDialogVisible: false,
      selectedApproval: '',
      approvalRow: null,
      approvalOpinion: '',
      // 学生报名信息导入参数
      upload: {
        // 是否显示弹出层（学生报名信息导入）
        open: false,
        // 弹出层标题（学生报名信息导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/registration/importData"
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生报名信息列表 */
    getList() {
      this.loading = true;
      listRegistration(this.queryParams).then(response => {
        this.registrationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        idNumber: null,
        grade: null,
        competitionGroup: null,
        competitionNumber: null,
        workType: null,
        otherWorkType: null,
        workName: null,
        school: null,
        parentName: null,
        parentPhone: null,
        thumbnail: null,
        preliminaryReview: null,
        firstReview: null,
        finalReview: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null  ,
        address: null,
        height: null,
        width: null,
        teacher: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生报名信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRegistration(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生报名信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查 thumbnail 是否为数组
          if (Array.isArray(this.form.thumbnail)) {
            this.form.thumbnail = this.form.thumbnail.join(',');
          }
          if (this.form.id != null) {
            updateRegistration(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegistration(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生报名信息编号为"' + ids + '"的数据项？').then(function() {
        return delRegistration(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/registration/export', {
        ...this.queryParams
      }, `registration_${new Date().getTime()}.xlsx`)
    },
    showApprovalDialog(row) {
      this.approvalRow = row;
      this.selectedApproval = '';
      this.approvalOpinion = ''; // 清空审批意见
      this.approvalDialogVisible = true;
    },
    handleApprove() {
      if (this.selectedApproval) {
        // 这里可以添加审批结果的处理逻辑，例如更新状态
        this.approvalRow.firstReview = this.selectedApproval;
        this.approvalRow.firstOption = this.approvalOpinion; // 保存审批意见
        updateRegistration(this.approvalRow).then(response => {
          this.$modal.msgSuccess("审批成功");
          this.approvalDialogVisible = false;
          this.getList(); // 更新列表
        });
      } else {
        this.$modal.msgWarning("请选择审批结果");
      }
    },
    isVideo(filePath) {
      const extension = filePath.split('.').pop().toLowerCase();
      return this.videoExtensions.includes(extension);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学生报名信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('project/registration/importTemplate', {
      }, `学生信息导入${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

  }
};
</script>
